﻿using Zws.Common;
using Zws.Redis;

namespace App.Chat.Auth
{
    public class AuthorizeMiddleware
    {
        private readonly RequestDelegate _next;

        public AuthorizeMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var isNeedLogin = context.GetEndpoint()?.Metadata
            .Where(x => x is NeedAuthAttribute).Any();
            if (isNeedLogin ?? false)
            {
                var token = context.GetLoginToken();
                var redis = context.RequestServices.GetService<RedisClient>();
                if (token == null || redis == null || !(await redis.IsExistAsync(token)))
                {
                    context.Response.StatusCode = StatusCodes.Status200OK;
                    await context.Response.WriteAsJsonAsync(ApiResult<string>.AuthResult("请登录。。。"));
                    return;
                }
            }
            await _next(context);
        }
    }
}
